<?php
/*-------------------------------------------------------------------------\
|
|  ========================================================
|  Fusion Registry GPL
|  Copyright (C) 2007 Fusion Scripts
|
|  This program is free software; you can redistribute it and/or
|  modify it under the terms of the GNU General Public License
|  as published by the Free Software Foundation; either version 2
|  of the License, or (at your option) any later version.
|
|  This program is distributed in the hope that it will be useful,
|  but WITHOUT ANY WARRANTY; without even the implied warranty of
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
|  GNU General Public License for more details.
|
|  You should have received a copy of the GNU General Public License
|  along with this program; if not, write to the Free Software
|  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
|  ========================================================
|
|  Email: info@fusionscripts.com
|  Web-Site: http://www.fusionscripts.com/
|
|  $Id: ad_custom_fields.php 4 2008-08-03 01:43:03Z registry.fusion $
|
\-------------------------------------------------------------------------*/

/**
 * This is the admin interface for custom fields of the Fusion Registry
 *
 * @package Fusion Registry
 * @subpackage admin
 * @version $Id: ad_custom_fields.php 4 2008-08-03 01:43:03Z registry.fusion $
 */

if ( ! defined( 'AD_REGISTRY_CALLED' ) )
{
    print "<h1>Incorrect access</h1>You cannot access this file directly.";
    exit();
}

/**#@+
 * Fusion Registry requires
 */
require_once(AD_REGISTRY_PATH.'ad_registry_loader.php');
require_once(REGISTRY_PATH.'lib/custom_fields.php');
/**#@-*/

/**
 * Class ad_registry_custom_fields deals with config & management of custom fields
 *
 * @package Fusion Registry
 * @subpackage admin
 */
class ad_registry_custom_fields
{
    var $ipsclass;

    /** @var string */
    var $base_url;

    /** @var object */
    var $ad_registry_loader;

    /** @var array */
    var $lib = array();

    /**
     * Intialization of ad_registry_fields
     *
     * Another traffic cop function, there should be minimal procedural code
     * here.
     */
    function auto_run()
    {
        // Kill globals
        $tmp_in = array_merge( $_GET, $_POST, $_COOKIE );

        foreach ( $tmp_in as $k => $v )
        {
            unset($$k);
        }

        // Initialize ad_registry_loader and registry_functions
        $this->ad_registry_loader = new ad_registry_loader();
        $this->ad_registry_loader->ipsclass =& $this->ipsclass;
        $this->ad_registry_loader->auto_run(&$this);

        $this->lib['custom_fields'] = new registry_custom_fields();
        $this->lib['custom_fields']->ipsclass =& $this->ipsclass;
        $this->lib['custom_fields']->auto_run(&$this);

        switch($this->ipsclass->input['code'])
        {
            case 'new':
                $this->do_form('new');
                break;
            case 'donew':
                $this->do_new();
                break;
            //-----------------------------------------
            case 'edit':
                $this->do_form('edit');
                break;
            case 'doedit':
                $this->do_edit();
                break;
            //-----------------------------------------
            case 'delete':
                $this->do_delete();
                break;
            //-----------------------------------------
            case 'group_new':
                $this->do_group_form('new');
                break;
            case 'group_donew':
                $this->do_group_new();
                break;
            //-----------------------------------------
            case 'group_edit':
                $this->do_group_form('edit');
                break;
            case 'group_doedit':
                $this->do_group_edit();
                break;
            //-----------------------------------------
            case 'group_delete':
                $this->do_group_delete();
                break;
            //-----------------------------------------
            case 'update_highlight':
                $this->do_update_highlight();
                break;
            //-----------------------------------------
            default:
                $this->show_fields();
                break;
        }

    }


    /**
     * Delete custom field
     */
    function do_delete()
    {
        $this->ipsclass->input['f'] = intval($this->ipsclass->input['f']);

        if ( ! $this->ipsclass->input['f'] )
        {
            $this->ipsclass->admin->error("Could not determine the source custom field ID.");
        }

        // Grab current info
        $field = $this->ipsclass->DB->simple_exec_query( array( 'select' => '*', 'from' => 'registry_field_defs', 'where' => 'field_id='.$this->ipsclass->input['f'] ) );

        if ($field['field_id'] == "")
        {
            $this->ipsclass->admin->error("Could not retrieve the custom field data based on ID {$this->ipsclass->input['f']}");
        }

        // Delete the field definition
        $this->ipsclass->DB->simple_exec_query( array( 'delete' => 'registry_field_defs', 'where' => "field_id=".$this->ipsclass->input['f'] ) );

        // Delete any end-user entries, if any..
        $this->ipsclass->DB->simple_exec_query( array( 'delete' => 'registry_field_entries', 'where' => "field_id=".$this->ipsclass->input['f'] ) );

        $this->ipsclass->admin->save_log("Fusion Registry Custom Field '{$field['field_name']}' removed");

        $this->ipsclass->admin->done_screen("Fusion Registry Custom Field '{$field['field_name']}' removed", "Fusion Registry Custom Field Management", "act=".REGISTRY_URL."&section=components&menu=custom_fields", 'redirect' );
    }


    /**
     * Create new custom field
     */
    function do_new()
    {
        $this->ipsclass->input['field_name'] = trim($this->ipsclass->input['field_name']);

        if ($this->ipsclass->input['field_name'] == "")
        {
            $this->ipsclass->admin->error("You must enter a Custom Field name");
        }

        $this->ipsclass->DB->do_insert( 'registry_field_defs',
                                        array( 'field_name'     => $this->ipsclass->input['field_name'],
                                               'field_type'     => $this->ipsclass->input['field_type'],
                                               'field_options'  => $this->ipsclass->my_br2nl( $this->ipsclass->input['field_options'] ),
                                               'field_default'  => $this->ipsclass->input['field_default'],
                                               'field_required' => $this->ipsclass->input['field_required'],
                                               'field_size'     => $this->ipsclass->input['field_size'],
                                               'field_rows'     => $this->ipsclass->input['field_rows'],
                                               'field_cols'     => $this->ipsclass->input['field_cols'],
                                               'field_order'    => $this->ipsclass->input['field_order'],
                                               'field_browse'   => $this->ipsclass->input['field_browse'],
                                               'field_search'   => $this->ipsclass->input['field_search'],
                                      )      );

        $this->ipsclass->admin->save_log("Fusion Registry Custom Field '{$this->ipsclass->input['field_name']}' created");

        $this->ipsclass->admin->done_screen("Fusion Registry Custom Field '{$this->ipsclass->input['field_name']}' created", "Fusion Registry Custom Field Management", "act=".REGISTRY_URL."&section=components&menu=custom_fields", 'redirect' );
    }


    /**
     * Display HTML form for adding or editing custom field
     *
     * If $type is 'edit' we query for the current data to populate
     * into the HTML form.
     *
     * @param string $type Pass in 'edit' to query for existing data, any other value will show form for adding new custom field
     */
    function do_form($type='edit')
    {
        $cf_help = "This section will allow you to add or edit an existing custom field.<br /><br />";

        // Add key to help people out
        $cf_help .= '<b>Quick Options Help - </b><br /><br />'.
                    'For Radio Buttons, Select Lists and Check Boxes enter options like this:<br />'.
                    'value1|Display1<br />'.
                    'value2|Display2<br />'.
                    'Where <i>value</i> is what is stored in the database, and <i>Display</i> '.
                    'is what is shown to end users. You can change the <i>Display</i> value at any time and not '.
                    'affect existing entries in the database. Enter one <i>value|Display</i> option per line.<br /><br >'.

                    'For special built-in fields you have the following choices available (these are for supporting legacy '.
                    'fields for automotive related sites):<br />'.
                    '<i>year</i> - This will create a populated select list<br />'.
                    '<i>make</i> - This will create the automotive Make field controlled via javascript<br />'.
                    '<i>model</i> - This will create the automative Model field controlled via javascript<br /><br />'.

                    '<b>NOTE: For the make/model special fields to work you MUST create both of them!</b>';

        if ( $type == 'edit' )
        {
            if ($this->ipsclass->input['f'] == "")
            {
                $this->ipsclass->admin->error("You didn't choose a custom field to edit, duh!");
            }

            // Go get our Custom Field definition
            $cf_data = $this->lib['custom_fields']->get_cf_defs( array( 'WHERE' => 'field_id='.$this->ipsclass->input['f'] ) );

            // Since get_cf_defs() returns an array of arrays, we are removing a layer here.
            //   The key is the field_id which was passed in from the beginning ;)
            $field = $cf_data[$this->ipsclass->input['f']];

            if ($field['field_id'] == "")
            {
                $this->ipsclass->admin->error("Could not retrieve the custom field data based on ID {$this->ipsclass->input['f']}");
            }

            $title  = "Editing Custom Field: {$field['field_name']}";
            $code   = "doedit";
        }
        else
        {
            $title  = "Add a Custom Field";
            $code   = "donew";
        }

        $field_types = $this->field_types_list();

        $this->ipsclass->html .= $this->ipsclass->skin_acp_global->information_box( $title, $cf_help.'<br />&nbsp;' ) . "<br >";

        $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'code', $code                 ),
                                                                             2 => array( 'act' , REGISTRY_URL          ),
                                                                             3 => array( 'f'   , $this->ipsclass->input['f'] ),
                                                                             4 => array( 'menu', 'custom_fields'       ),
                                                                             5 => array( 'section', 'components' ),
                                                                    )      );

        $this->ipsclass->adskin->td_header[] = array( "{none}"  , "40%" );
        $this->ipsclass->adskin->td_header[] = array( "{none}"  , "60%" );

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( $title );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Name</b>" ,
                                                                 $this->ipsclass->adskin->form_input("field_name", $field['field_name'])
                                                        )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Type</b>" ,
                                                                 $this->ipsclass->adskin->form_dropdown("field_type", $field_types, $field['field_type'])
                                                        )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Options</b><div style='color:gray'>Applies to: Radio Buttons, Select Lists, Check Boxes, and Special built-in fields.</div>" ,
                                                                 $this->ipsclass->adskin->form_textarea("field_options", $this->ipsclass->my_br2nl( $field['field_options']) )
                                                        )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Default</b>" ,
                                                                 $this->ipsclass->adskin->form_input("field_default", $field['field_default'])
                                                        )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Required?</b>" ,
                                                                 $this->ipsclass->adskin->form_yes_no("field_required", $field['field_required'])
                                                        )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Max Size</b><div style='color:gray'>Applies to: Text (one line) fields and Money (floating point) fields.<br />NOTE: Default is 255.</div>" ,
                                                                 $this->ipsclass->adskin->form_input("field_size", $field['field_size'])
                                                        )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Rows</b><div style='color:gray'>Applies to: Memo/Textarea fields.<br />NOTE: Default is 10.</div>" ,
                                                                 $this->ipsclass->adskin->form_input("field_rows", $field['field_rows'])
                                                        )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Columns</b><div style='color:gray'>Applies to: Memo/Textarea fields.<br />NOTE: Default is 60.</div>" ,
                                                                 $this->ipsclass->adskin->form_input("field_cols", $field['field_cols'])
                                                        )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Show on Browse Screen?</b>" ,
                                                                 $this->ipsclass->adskin->form_yes_no("field_browse", $field['field_browse'])
                                                        )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Searchable?</b>" ,
                                                                 $this->ipsclass->adskin->form_yes_no("field_search", $field['field_search'])
                                                        )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Order</b>" ,
                                                                 $this->ipsclass->adskin->form_input("field_order", $field['field_order'])
                                                        )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        if ( $type == 'edit' )
        {
            $this->ipsclass->html .= $this->ipsclass->adskin->end_form_standalone("Edit this Custom Field");
        }
        else
        {
            $this->ipsclass->html .= $this->ipsclass->adskin->end_form_standalone("Create this Custom Field");

            $this->ipsclass->html .= $this->ipsclass->adskin->end_table();
        }

        $this->ipsclass->admin->nav[] = array( 'act='.REGISTRY_URL.'&section=components&menu=custom_fields', 'Manage Fusion Registry Custom Fields' );
        $this->ipsclass->admin->nav[] = array( '', 'Add/Edit Custom Field' );

        $this->ipsclass->admin->output();
    }


    /**
     * Save the changes made to a custom field
     */
    function do_edit()
    {
        $this->ipsclass->input['field_name'] = trim($this->ipsclass->input['field_name']);

        if ($this->ipsclass->input['field_name'] == "")
        {
            $this->ipsclass->admin->error("You must enter a Custom Field name");
        }

        $this->ipsclass->DB->do_update( 'registry_field_defs',
                                        array( 'field_name'     => $this->ipsclass->input['field_name'],
                                               'field_type'     => $this->ipsclass->input['field_type'],
                                               'field_options'  => $this->ipsclass->my_br2nl( $this->ipsclass->input['field_options'] ),
                                               'field_default'  => $this->ipsclass->input['field_default'],
                                               'field_required' => $this->ipsclass->input['field_required'],
                                               'field_size'     => $this->ipsclass->input['field_size'],
                                               'field_rows'     => $this->ipsclass->input['field_rows'],
                                               'field_cols'     => $this->ipsclass->input['field_cols'],
                                               'field_order'    => $this->ipsclass->input['field_order'],
                                               'field_browse'   => $this->ipsclass->input['field_browse'],
                                               'field_search'   => $this->ipsclass->input['field_search'] ),
                                        "field_id={$this->ipsclass->input['f']}" );

        $this->ipsclass->admin->save_log("Fusion Registry Custom Field '{$this->ipsclass->input['field_name']}' edited");

        $this->ipsclass->admin->done_screen("Fusion Registry Custom Field '{$this->ipsclass->input['field_name']}' edited", "Fusion Registry Custom Field Management", "act=".REGISTRY_URL."&section=components&menu=custom_fields", 'redirect' );
    }


    /**
     * Delete custom field group
     *
     * This isn't actually deleting anything, it's just setting the
     * field_group_id column to NULL.
     */
    function do_group_delete()
    {
        // Sanitize the variable
        $this->ipsclass->input['g'] = intval( $this->ipsclass->input['g'] );

        if ( !$this->ipsclass->input['g'] )
        {
            $this->ipsclass->admin->error("Something went wrong, we didn't get a group_id sent to us, please return to the Custom Fields main menu and try again.");
        }

        // Wipe out this group, this is all that we have to do, really ;)
        $this->ipsclass->DB->query( "UPDATE ibf_registry_field_defs SET field_group_id = NULL WHERE field_group_id='".$this->ipsclass->input['g']."'" );

        $this->ipsclass->admin->save_log("Fusion Registry Custom Field Group id '{$this->ipsclass->input['g']}' deleted");

        $this->ipsclass->admin->done_screen("Fusion Registry Custom Field Group id '{$this->ipsclass->input['g']}' deleted", "Fusion Registry Custom Field Management", "act=".REGISTRY_URL."&section=components&menu=custom_fields", 'redirect' );
    }


    /**
     * Save the changes made to a custom field group
     *
     * This function resets which custom fields are in a group. This
     * is done by first setting the field_group_id to NULL for the custom
     * field group, then updating all the custom fields the user selected
     * to be in this custom field group.
     */
    function do_group_edit()
    {
        // Sanitize the variable
        $this->ipsclass->input['g'] = intval( $this->ipsclass->input['g'] );

        if ( !$this->ipsclass->input['g'] )
        {
            $this->ipsclass->admin->error("Something went wrong, we didn't get a group_id sent to us, please return to the Custom Fields main menu and try again.");
        }

        // First Wipe out this group, then we will reset the fields
        $this->ipsclass->DB->query( "UPDATE ibf_registry_field_defs SET field_group_id = NULL WHERE field_group_id='".$this->ipsclass->input['g']."'" );

        // Gather the list of fields to apply to this group
        $field_list = '(';

        foreach ( $this->ipsclass->input['cf_group_fields'] as $field_id )
        {
            $field_list .= "'$field_id', ";
        }

        // Get rid of the last comma
        $field_list = substr($field_list, 0, -2);

        // Polish off the syntax
        $field_list .= ')';

        $this->ipsclass->DB->do_update( 'registry_field_defs', array( 'field_group_id' => $this->ipsclass->input['g'] ), "field_id IN $field_list" );

        $this->ipsclass->admin->save_log("Fusion Registry Custom Field Group id '{$this->ipsclass->input['g']}' edited");

        $this->ipsclass->admin->done_screen("Fusion Registry Custom Field Group id '{$this->ipsclass->input['g']}' edited", "Fusion Registry Custom Field Management", "act=".REGISTRY_URL."&section=components&menu=custom_fields", 'redirect' );
    }


    /**
     * Show HTML for adding or editing a custom field group
     *
     * If $type is 'edit' we query for the current data to populate
     * into the HTML form.
     *
     * @param string $type Pass in 'edit' to query for existing data, any other value will show form for adding new custom field group
     */
    function do_group_form($type='edit')
    {
        if ( $type == 'edit' )
        {
            if ($this->ipsclass->input['g'] == "")
            {
                $this->ipsclass->admin->error("You didn't choose a custom field group to edit, duh!");
            }

            // Get all fields that are either in this group or in no group
            $query = 'SELECT field_group_id, field_id, field_name FROM ibf_registry_field_defs '.
                     "WHERE ( field_group_id = '".intval($this->ipsclass->input['g'])."' OR field_group_id IS NULL ) ".
                     'ORDER BY field_order ASC, field_name ASC';

            $title  = "Editing Custom Field Group";
            $code   = "group_doedit";
        }
        else
        {
            // Get all fields that aren't in any groups
            $query = 'SELECT field_group_id, field_id, field_name FROM ibf_registry_field_defs '.
                     'WHERE field_group_id IS NULL '.
                     'ORDER BY field_order ASC, field_name ASC';

            $title  = "Add a Custom Field Group";
            $code   = "group_donew";
        }

        $this->ipsclass->html .= $this->ipsclass->skin_acp_global->information_box( $title, "This section will allow you to add or edit an existing custom field group. Custom fields can only be in one custom field group at a time, so the available fields to add to the group below will exclude any already present in other groups.".'<br />&nbsp;' ) . "<br >";

        // Now let's plop in the dynamic query for either the new/edit group form
        $rs = $this->ipsclass->DB->query($query);

        if ( !$this->ipsclass->DB->get_num_rows() )
        {
            switch( $type )
            {
                case 'edit':
                    $this->ipsclass->admin->error('Something went wrong, please return to the Custom Field main menu and try again.');
                    break;

                case 'new':
                    $this->ipsclass->admin->error('All Custom Fields are already in groups, therefore there are no more groups to be defined ;)');
                    break;
            }
        }

        $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'code', $code                 ),
                                                                             2 => array( 'act' , REGISTRY_URL          ),
                                                                             3 => array( 'g'   , $this->ipsclass->input['g'] ),
                                                                             4 => array( 'menu', 'custom_fields'       ),
                                                                             5 => array( 'section', 'components'       ),
                                                        )      );

        $this->ipsclass->adskin->td_header[] = array( "{none}"  , "5%" );
        $this->ipsclass->adskin->td_header[] = array( "{none}"  , "90%" );

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( $title );

        while ( $row = $this->ipsclass->DB->fetch_row($rs) )
        {
            $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( '<center>'.$this->ipsclass->adskin->form_checkbox('cf_group_fields[]', ( !empty($row['field_group_id']) ) ? 1 : 0, $row['field_id']) .'</center>',
                                                                     $row['field_name']
                                                            )      );
        }

        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        if ( $type == 'edit' )
        {
            $this->ipsclass->html .= $this->ipsclass->adskin->end_form_standalone("Edit this Custom Field Group");
        }
        else
        {
            $this->ipsclass->html .= $this->ipsclass->adskin->end_form_standalone("Create this Custom Field Group");

            $this->ipsclass->html .= $this->ipsclass->adskin->end_table();
        }

        $this->ipsclass->admin->nav[] = array( 'act='.REGISTRY_URL.'&section=components&menu=custom_fields', 'Manage Fusion Registry Custom Fields' );
        $this->ipsclass->admin->nav[] = array( '', 'Add/Edit Custom Field Groups' );

        $this->ipsclass->admin->output();
    }


    /**
     * Create a new custom field group
     *
     * This doesn't actually create anything, it just updates the
     * field_group_id in the DB. Generating the group id is currently
     * not controlled by mysql, but by selecting the current MAX()
     * value and incrementing it. Although this is not the best way,
     * it has a very low likely-hood of causing problems. Two admins
     * would have to be adding a new custom field group at the exact
     * same time.
     */
    function do_group_new()
    {
        // Make sure we got at least one field passed to us
        if ( count($this->ipsclass->input['cf_group_fields']) < 1 )
        {
            $this->ipsclass->admin->error("You have to select at least one Custom Field to create a new Custom Field Group.");
        }

        // We are using the poor man's solution, self-generate our new group id
        $max_group = $this->ipsclass->DB->simple_exec_query( array( 'select' => 'MAX(field_group_id) AS max_group_num', 'from' => 'registry_field_defs' ) );

        $new_group_id = $max_group['max_group_num'] + 1;

        if ( $new_group_id < 1 )
        {
            $this->ipsclass->admin->error("Something went wrong, I was unable to determine the new field_group_id, please return to the Custom Fields main menu and try again.");
        }

        // Gather the list of fields to apply to this group
        $field_list = '(';

        foreach ( $this->ipsclass->input['cf_group_fields'] as $field_id )
        {
            $field_list .= "'$field_id', ";
        }

        // Get rid of the last comma
        $field_list = substr($field_list, 0, -2);

        // Polish off the syntax
        $field_list .= ')';

        $this->ipsclass->DB->do_update( 'registry_field_defs', array( 'field_group_id' => $new_group_id ), "field_id IN $field_list" );

        $this->ipsclass->admin->save_log("Fusion Registry Custom Field Group id '{$new_group_id}' Added");

        $this->ipsclass->admin->done_screen("Fusion Registry Custom Field Group id '{$new_group_id}' Added", "Fusion Registry Custom Field Management", "act=".REGISTRY_URL."&section=components&menu=custom_fields", 'redirect' );
    }


    /**
     * Update the chosen highlighted custom field(s)/group
     */
    function do_update_highlight()
    {
        if ( !$this->ipsclass->input['field_highlight'] )
        {
            $this->ipsclass->admin->error("Something went wrong, we didn't get a highlight selection sent to us, please return to the Custom Fields main menu and try again.");
        }

        // Wipe out any current highlight
        $this->ipsclass->DB->query( 'UPDATE ibf_registry_field_defs SET field_highlight = NULL' );

        // Incase we got a group, explode them ids
        $highlight_ids = explode( ",", $this->ipsclass->input['field_highlight'] );

        foreach ( $highlight_ids as $field_id )
        {
            $this->ipsclass->DB->query( "UPDATE ibf_registry_field_defs SET field_highlight='1' WHERE field_id='$field_id'" );
        }

        $this->ipsclass->admin->save_log("Fusion Registry Custom Field Highlight fields '".$this->ipsclass->input['field_highlight']."' set");

        $this->ipsclass->admin->done_screen("Fusion Registry Custom Field Highlight fields '".$this->ipsclass->input['field_highlight']."' set", "Fusion Registry Custom Field Management", "act=".REGISTRY_URL."&section=components&menu=custom_fields", 'redirect' );
    }


    /**
     * The main menu of the custom fields page
     */
    function show_fields()
    {
        // Grab all the custom field definitions and groups first as they will be used by a few things below
        $cf_defs   = $this->lib['custom_fields']->get_cf_defs( array( 'ORDER BY' => 'field_order ASC, field_name ASC' ) );
        $cf_groups = $this->lib['custom_fields']->get_cf_groups();

        $this->ipsclass->html .= $this->ipsclass->skin_acp_global->information_box( "Fusion Registry Custom Fields Overview", "You can manage your garage custom fields from here.<br /><br /><span style='color:red'><b>PLEASE NOTE:</b> You must not configure the same order number for more than 1 custom field. Doing so will result in some of your custom fields from not showing up!</span>".'<br />&nbsp;' ) . "<br >";

        // Get the processed list of all custom fields and groups
        $cf_processed = $this->lib['custom_fields']->process_cf_defs( array( 'cf_defs' => $cf_defs, 'cf_groups' => $cf_groups, 'type' => 'acp_highlight' ) );

        // Get the current highlighted field
        $cf_highlight = $this->lib['custom_fields']->get_cf_highlight();

        // HTML headers
        $this->ipsclass->adskin->td_header[] = array( "Edit"     , "6%"  );
        $this->ipsclass->adskin->td_header[] = array( "Delete"   , "6%"  );
        $this->ipsclass->adskin->td_header[] = array( "Name"     , "18%" );
        $this->ipsclass->adskin->td_header[] = array( "Type"     , "5%"  );
        $this->ipsclass->adskin->td_header[] = array( "Options"  , "18%" );
        $this->ipsclass->adskin->td_header[] = array( "Default"  , "9%"  );
        $this->ipsclass->adskin->td_header[] = array( "Require"  , "6%"  );
        $this->ipsclass->adskin->td_header[] = array( "Size"     , "5%"  );
        $this->ipsclass->adskin->td_header[] = array( "Rows"     , "5%"  );
        $this->ipsclass->adskin->td_header[] = array( "Cols"     , "5%"  );
        $this->ipsclass->adskin->td_header[] = array( "Browse"   , "6%"  );
        $this->ipsclass->adskin->td_header[] = array( "Search"   , "6%"  );
        $this->ipsclass->adskin->td_header[] = array( "Order"    , "5%"  );

        $this->ipsclass->html .=
        "<script type='text/javascript'>
            <!--
            function confirm_delete_field( field_id )
            {
                if ( confirm('Are you sure you want to delete this Fusion Registry Custom Field and all end user records associated with it? This operation is not undo-able!') )
                {
                    window.location.href = '{$this->ipsclass->base_url}&act=".REGISTRY_URL."&section=components&menu=custom_fields&code=delete&f=' + field_id;
                }
            }

            function confirm_delete_field_group( group_id )
            {
                if ( confirm('Are you sure you want to delete this Fusion Registry Custom Field Group? This operation is not undo-able!') )
                {
                    window.location.href = '{$this->ipsclass->base_url}&act=".REGISTRY_URL."&section=components&menu=custom_fields&code=group_delete&g=' + group_id;
                }
            }
            // -->
        </script> ";

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Fusion Registry Custom Fields" );

        // Loop through our custom field definitions we got from up above
        foreach ( $cf_defs as $cf_id => $cf_row )
        {
            $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( '<center><a href="'.$this->ipsclass->base_url.'&amp;act='.REGISTRY_URL.'&section=components&menu=custom_fields&amp;code=edit&amp;f='.$cf_row['field_id'].'">'. $this->ad_registry_loader->imgs['edit'] .'</a></center>',
                                                                     '<center><a href="javascript:confirm_delete_field( '.$cf_row['field_id'].' )">'. $this->ad_registry_loader->imgs['delete'] .'</a></center>',
                                                                     $cf_row['field_name'],
                                                                     '<center>'.$cf_row['field_type'].'</center>',
                                                                     $this->ipsclass->my_nl2br( $cf_row['field_options'] ),
                                                                     $cf_row['field_default'],
                                                                     $cf_row['field_required'] ? 'Y' : 'N',
                                                                     $cf_row['field_size'],
                                                                     $cf_row['field_rows'],
                                                                     $cf_row['field_cols'],
                                                                     $cf_row['field_browse'] ? 'Y' : 'N',
                                                                     $cf_row['field_search'] ? 'Y' : 'N',
                                                                     $cf_row['field_order'],
                                                            )      );
        }

        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        $html = $this->ipsclass->adskin->js_make_button("Add New Custom Field", $this->ipsclass->base_url."&amp;act=".REGISTRY_URL."&section=components&menu=custom_fields&amp;code=new");

        $this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($html, 'left');

        $this->ipsclass->html .= '<br /><br />';

        // Now are groups table
        $this->ipsclass->adskin->td_header[] = array( "Edit"                  , "6%" );
        $this->ipsclass->adskin->td_header[] = array( "Delete"                , "6%" );
        $this->ipsclass->adskin->td_header[] = array( "Custom Fields in Group", "88%" );

        $desc = "Grouping Custom Fields together allows you to tie fields that are related to be displayed on the same line. For example the make and model of a vehicle. The order in which the fields are displayed within the group is determined by their overall order number. The overall order of the group is determined by the order number of the first custom field in the group.";

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Fusion Registry Custom Field Groups", $desc );

        // We just want to display the field names, so loop through and make a string of the field_names
        foreach ( $cf_groups as $cf_group_fields )
        {
            $group_fields = '';
            foreach ( $cf_group_fields as $cf )
            {
                $group_fields .= $cf['field_name'].' / ';
            }

            // Strip off last slash
            $group_fields = substr($group_fields, 0, -3);

            $cf_group_id = $cf_group_fields[0]['field_group_id'];

            $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( '<center><a href="'.$this->ipsclass->base_url.'&amp;act='.REGISTRY_URL.'&section=components&menu=custom_fields&amp;code=group_edit&amp;g='.$cf_group_id.'">'. $this->ad_registry_loader->imgs['edit'] .'</a></center>',
                                                                     '<center><a href="javascript:confirm_delete_field_group( '.$cf_group_id.' )">'. $this->ad_registry_loader->imgs['delete'] .'</a></center>',
                                                                     $group_fields,
                                                            )      );
        }

        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        $html = $this->ipsclass->adskin->js_make_button("Add New Custom Field Group", $this->ipsclass->base_url."&amp;act=".REGISTRY_URL."&section=components&menu=custom_fields&amp;code=group_new");

        $this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($html, 'left');

        $this->ipsclass->html .= '<br /><br />';

        // Highlight menu
        $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'code', 'update_highlight' ),
                                                                             2 => array( 'act' , REGISTRY_URL       ),
                                                                             3 => array( 'menu', 'custom_fields'    ),
                                                                             4 => array( 'section', 'components'    ),
                                                                    )      );

        $this->ipsclass->adskin->td_header[] = array( "{none}"   , "30%" );
        $this->ipsclass->adskin->td_header[] = array( "{none}"   , "70%" );

        $desc = 'The Custom Field or Group chosen as the Highlighted item will be shown first in the list of fields regardless of overall order. It will also be used as the title of the table and page when viewing a vehicle in the Fusion Registry. Commonly this would be setup as the Year/Make/Model. If you do not set a highlight item the first Custom Field by order will be used as the highlight item.';

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Custom Field Highlight Controls", $desc );

        // Then for the sake of this form, just squish all the ids together
        $cf_highlight_ids = implode( ",", array_keys($cf_highlight) );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Highlighted Custom Field/Group</b>",
                                                                             $this->ipsclass->adskin->form_dropdown('field_highlight', $cf_processed, $cf_highlight_ids)
                                                                    )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->end_form("Update Highlight");

        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        $this->ipsclass->admin->nav[] = array( '', 'Manage Fusion Registry Custom Fields' );

        $this->ipsclass->admin->output();
    }


    /**
     * Return an array of all the custom field types
     *
     * This should be the only place in the code that defines the
     * single letter key and value for all the supported custom field
     * types.
     *
     * @return array An array of arrays describing all supported custom field types
     */
    function field_types_list()
    {
        $field_array = array( array( 'T', 'Text (one line)'        ),
                              array( 'M', 'Memo/Textarea'          ),
                              array( 'F', 'Money (floating point)' ),
                              array( 'R', 'Radio Buttons'          ),
                              array( 'C', 'Check Boxes'            ),
                              array( 'L', 'Select List'            ),
                              array( 'S', 'Special built-in field' ),
                            );

        return $field_array;
    }
}
?>